// pages/orderPay/pay.js
const { esprima } = require('../../esprima.js');
const app = getApp();
Page({

  data: {
    bgTextStyle: 'dark',
    scrollTop: '200rpx',
    bgColor: '#f1f1f1',
    bgColorTop: '#00ff00',
    bgColorBottom: '#0000ff',
    nbTitle: '供热缴费',
    nbLoading: false,
    nbFrontColor: '#000000',
    nbBackgroundColor: '#ffffff',
    pageStyle: "color:#333333;background-color: #f1f1f1;",
    indicatorDots: false,
    vertical: false,
    autoplay: false,
    interval: 2000,
    duration: 500,
    background: [
      {img: "https://spgs.int-great.cn/upfile/imgs/87/df6fe860a8874a03ec38ddb9b34fb7f2.jpg"}
    ],
    userInfo: {
      nickName: "",
      addr: "",
      phone: "",
      avatar: ""
    },
    ownerInfo: {
      addr: "",
      phone: "",
      username: "",
      heat_code: ""
    },
    binds: [],
    bindStr: [],
    index : 0,
    heat_code: "",
    company: "北京融乐物业管理有限公司",
    text: '',
    agree: false,
    showMode: false,
    enableCheck: true,
    payMoney: '',
    orderList: [
      // {id:0, year: "2021", money: "155.55",date:"2021-11 到 2022-03", payed: false}
    ],
    waitPay: false,
    hasRequest: false,
    ready: false
  },
  onLoad: function (options) {
    console.log(options);
  },
  onReady: function () {

  },
  onShow: function (options) {
    let v = this;
    // console.log("onShow",options);
    v.getStorage();
    v.getSwiper();
  },
  getStorage(){
    let v = this;
    let menu = wx.getStorageSync('menu');
    // console.log('getStorageSync menu',menu);
    if(menu && menu.title) {
      v.setData({nbTitle: menu.title});
    }
    if(app.globalData.userInfo) {
      // console.log('app.globalData.userInfo',app.globalData.userInfo);
      if(app.globalData.userInfo.heat_code) {
        let heat_code = app.globalData.userInfo.heat_code;
        v.setData({heat_code: heat_code, binds: [heat_code],userInfo: app.globalData.userInfo});
        
        // v.getText();
        // v.getOrderList();
      }
      v.getMyBinds();
      v.getText();
    }
  },
  getText(){
    let v = this;
    let url = app.globalData.host + '/api/common/text';
    wx.request({
      url: url, data: {id:2, token: app.globalData.token},
      success (res) {
        let r = res.data;
        if(r.code == 200 && r.data) {
          let dd = r.data;
          let txt = dd[2];
          console.log('getText',txt,dd);
          v.setData({text: txt});
        }
      }
    })
  },
  showText(){
    let v = this;
    console.log("showText",v.data.showMode);
    v.setData({showMode: !v.data.showMode});
  },
  checkboxChange(ev){
    let v = this;
    let val = ev.detail.value;
    console.log("checkboxChange",val);
    v.setData({agree: !v.data.agree});
  },
  getMyBinds: function() {
    let v = this;
    let url = app.globalData.host + '/api/user/owner_list';
    wx.request({
      url: url, data: {token: app.globalData.token},
      success (res) {
        let r = res.data;
        if(r.code == 200 && r.data) {
          let l = r.data.list || [];
          let s = [];
          let index = 0;
          for(let i = 0, il = l.length; i < il; i++) {
            l[i].checked = (i == 0);
            s.push(l[i].username);
            if(l[i].default) index = i;
          }
          console.log("getMyBinds",l,s);
          v.setData({binds: l,bindStr: s});
          //v.getOrderList();
          
          v.bindPickerChange({detail: {value: index}});
        }
      }
    })
  },
  switchCode(){
    let v = this;
    // v.setData({binds: []});
  },
  bindPickerChange(ev){
    let v = this;
    let l = v.data.binds || [];
    console.log("bindPickerChange",ev);
    let id = parseInt(ev.detail.value);
    
    if(!l[id]) return;
    let owner_id = l[id].owner_id;
    let heat_code = l[id].heat_code;
    let info = { addr: "", phone: "", username: "", heat_code: "" };
    v.setData({index: id, heat_code: heat_code});
    console.log("selected owner_id heat_code", owner_id, heat_code);
    // v.getOrderList();
  },
  bindInput(ev) {
    let v = this;
    let newVal  = ev.detail.value;
    if(newVal) {
      v.setData({heat_code: newVal,hasRequest:false});
      // v.setData({orderList: l, ownerInfo: r.data.owner, waitPay: waitPay, agree: false, hasRequest: true});
    }
    console.log('bindInput', newVal,ev);
  },
  getSwiper() {
    let v = this;
    let url = app.globalData.host + '/api/common/banner';
    wx.request({
      url: url,
      data: { page: 2},
      success (res) {
        // console.log(res.data);
        let r = res.data;
        if(r.code == 200 && r.data) {
          let l = r.data;
          let a = [];
          for(let i in l) {
            let it = {}; Object.assign(it, l[i]);
            a.push(it)
          }
          v.setData({background: a});
          console.log("getSwiper",a);
        }
      }
    })
  },
  getOrderList() {
    let v = this;
    let url = app.globalData.host + '/api/heat/payinfo';
    let bind = 0;
    let l = v.data.binds || [];
    for(let i = 0, il = l.length; i < il; i++) if(l[i].checked) bind = l[i].owner_id;
    if (l[v.data.index]) bind = l[v.data.index].owner_id;
    let data = {owner_id:bind, token: app.globalData.token};
    if(v.data.heat_code) {
      data = { heat_code:v.data.heat_code, token: app.globalData.token };
      if(!data.heat_code) {
        wx.showToast({ title: '请输入供暖编号',icon:'none' });
        return;
      }
    }
    v.setData({ownerInfo: {}});
    wx.request({
      url: url, data: data, 
      success (res) {
        let r = res.data;
        if(r.code == 200 && r.data) {
          console.log("bind_heat_code",r);
          let l = r.data.list;
          let waitPay = false;
          let selected = false;
          for(let k in l) {
            l[k].checked = true;
            l[k].value = l[k].payid;
            waitPay = true;
            if(l[k].money ) { // (l[k].status == 0)
              if (!selected) {
                l[k].checked = true;
                selected = true;
              }
            }
          }
          console.log('orderList',l);
          v.setData({orderList: l, ownerInfo: r.data.owner, waitPay: waitPay, agree: false, hasRequest: true});
          v.calcuMoney();
        } else {
          wx.showToast({ title: r.msg || '',icon:'none' });
        }
      },
      fail (err) { console.log('payinfo',err); }
    })
    console.log('getOrderList',bind);
  },
  radioChange(el){
    let v = this;
    console.log('radioChange', el);
    let payid = el.detail.value;
    let ll = v.data.orderList;
    for(let k in ll) {
      if(ll[k].payid == payid) {
        ll[k].checked = true;
      } else {
        ll[k].checked = false;
      }
    }
    v.calcuMoney();
  },
  calcuMoney(){
    let v = this;
    let ll = v.data.orderList;
    let payMoney = 0;
    for(let k in ll) {
      if(ll[k].checked) {
        payMoney += parseFloat(ll[k].money);
      }
    }
    v.setData({payMoney:payMoney.toFixed(2)});
    console.log("calcuMoney",payMoney);
  },
  //payMoney
  requestPay() {
    let v = this;
    console.log('requestPay');
    if(!v.data.agree) {
      wx.showToast({ title: '请先阅读缴费协议', icon: 'none'});
      return;
    }
    let owner_id = 0;
    let bl = v.data.binds || [];
    owner_id = v.data.ownerInfo.owner_id;
    let url = app.globalData.host + '/api/order/add';
    let payid = 0;
    let ll = v.data.orderList;
    for(let k in ll) if(ll[k].checked) payid = ll[k].payid;
    wx.request({
      url: url, data: {owner_id: owner_id,token: app.globalData.token,menu_id:1,payid: payid}, 
      success (res) {
        let r = res.data;
        if(r.code == 200 && r.data) {
          console.log("requestPay",r);
          let payinfo = r.data.payinfo;
          wx.requestPayment({
            timeStamp: payinfo.timeStamp,
            nonceStr: payinfo.nonceStr,
            package: payinfo.package,
            signType: payinfo.signType,
            paySign: payinfo.paySign,
            appId: payinfo.appId,
            success (res) { 
              console.log('requestPayment success',res);
              wx.showToast({ title: '缴费成功', icon: 'none', duration: 2000 });
              v.getOrderList();
            },
            fail (res) {
              console.log('requestPayment fail',res);
             }
          })
        } else {
          if(r.msg) wx.showToast({ title: r.msg, icon: 'none', duration: 2000 });
        }
      },
      fail (err) { console.log('requestPay',err); }
    })
  },
  saveCode() {
    let v= this;
    let url = app.globalData.host + '/api/user/bind_heat_code';
    let data = {token: app.globalData.token, heat_code: v.data.heat_code};
    wx.request({
      url: url, data: data,method: "GET",
      success (res) {
        let r = res.data;
        if(r.code == 200 && r.data) {
          console.log("bind_heat_code",r);
          v.setData({orderList: [], owner: {}, waitPay: false});
          app.doLogin(v, v.getStorage);
        }
        if(r.msg) wx.showToast({ icon: "none", title: r.msg });
      },
      fail (err) {
        wx.showToast({ icon: "none", title: '保存失败，请稍后再试~~', });
        console.log('saveInfo',err);
      }
    })
  },
  showNotice(){
    wx.showModal({
      title: '如何查户号?',
      content: '请联系供暖缴费单位获取供暖编号.',
      showCancel: false,
      confirmColor: '#57bB95',
      success (res) {
        if (res.confirm) {
          console.log('用户点击确定');
        } else if (res.cancel) {
          console.log('用户点击取消');
        }
      }
    })
  },
  navToBind(ev){
    let v = this;
    console.log("navToBind");
    wx.navigateTo({ url: "/pages/binds/binds"});
  },
  onHide: function () {

  },
  onUnload: function () {

  },
  onPullDownRefresh: function () {

  },
  onReachBottom: function () {

  },
  onShareAppMessage: function () {

  }
})